import {getBaseUrl, isDebug} from './env'

// 使用函数获取最新的 baseUrl
const getBaseURL = () => getBaseUrl()

function getToken() {
    return uni.getStorageSync('token') || null
}

function request(url, method = 'GET', data = {}, options = {}) {
    const token = getToken()
    const header = {
        'Content-Type': 'application/json',
        ...(token ? {Authorization: `Bearer ${token}`} : {})
    }

    if (options.showLoading) {
        uni.showLoading({title: '加载中...', mask: true})
    }

    // 获取当前环境的 baseUrl
    const baseUrl = getBaseURL()

    // 调试模式下，打印请求信息
    if (isDebug()) {
        console.log('Request:', {
            url: baseUrl + url,
            method,
            data,
            header
        })
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            method,
            data,
            header,
            ...options,
            success(res) {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                } else {
                    uni.showToast({title: res.data.message || '请求失败', icon: 'none'})
                    reject(res)
                }
            },
            fail(err) {
                uni.showToast({title: '网络异常', icon: 'none'})
                reject(err)
            },
            complete() {
                if (options.showLoading) uni.hideLoading()
            }
        })
    })
}

export const get = (url, data = {}, options = {}) => request(url, 'GET', data, options)
export const post = (url, data = {}, options = {}) => request(url, 'POST', data, options)
export const put = (url, data = {}, options = {}) => request(url, 'PUT', data, options)
export const del = (url, data = {}, options = {}) => request(url, 'DELETE', data, options)

export function uploadFile(url, filePath, name = 'file', formData = {}) {
    const token = getToken()
    const baseUrl = getBaseURL()

    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: baseUrl + url,
            filePath,
            name,
            formData,
            header: {
                Authorization: `Bearer ${token}`
            },
            success: res => {
                const data = JSON.parse(res.data)
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(data)
                } else {
                    reject(data)
                }
            },
            fail: err => reject(err)
        })
    })
}

export function downloadFile(url) {
    const token = getToken()
    const baseUrl = getBaseURL()

    return new Promise((resolve, reject) => {
        uni.downloadFile({
            url: baseUrl + url,
            header: {
                Authorization: `Bearer ${token}`
            },
            success: res => {
                if (res.statusCode === 200) {
                    resolve(res)
                } else {
                    reject(res)
                }
            },
            fail: err => reject(err)
        })
    })
}
